
/*-----------------------------------------------------------------------------
 * HEADER FILS
 *---------------------------------------------------------------------------*/
#include "gmi_i2c.h"

#include "gmi_gpio.h"

#ifdef __GMI_STM32__
#include "main.h"
#endif

/*-----------------------------------------------------------------------------
 * MACRO DEFINITIONS
 *---------------------------------------------------------------------------*/
#ifdef __GMI_STM32__
#define SLAVE_ID_WRITE(id) (((uint16_t)id << 1) & 0x00FE)
#define SLAVE_ID_READ(id)  (((uint16_t)id << 1) | 0x0001)
#endif

/*-----------------------------------------------------------------------------
 * FUNCTIONS DEFINITION
 *---------------------------------------------------------------------------*/

GMI_STATUS gmi_i2c_master_write_read(gmi_i2c_slave_config_t* slave,
                                     uint8_t* write_buffer,
                                     size_t write_size,
                                     uint8_t* read_buffer,
                                     size_t read_size)
{
    GMI_STATUS status = GMI_STATUS_OK;

    if (slave == NULL || slave->phandle == NULL || write_buffer == NULL)
    {
        status = GMI_STATUS_HANDLE_NULL;
        goto EXIT;
    }

    if (write_size > 65535 || write_size == 0)
    {
        status = GMI_STATUS_PARAM_INVALID;
        goto EXIT;
    }

#ifdef __GMI_STM32__

    status = (GMI_STATUS)HAL_I2C_Master_Transmit(
        (I2C_HandleTypeDef*)(slave->phandle),
        (uint16_t)SLAVE_ID_WRITE(slave->device_id),
        write_buffer,
        (uint16_t)write_size,
        10U);

    CHECK_STATUS(status);

    if (read_buffer != NULL)
    {
        if (read_size == 0 || read_size > 65535)
        {
            status = GMI_STATUS_PARAM_INVALID;
            goto EXIT;
        }

        status = (GMI_STATUS)HAL_I2C_Master_Receive(
            (I2C_HandleTypeDef*)(slave->phandle),
            (uint16_t)SLAVE_ID_READ(slave->device_id),
            read_buffer,
            (uint16_t)read_size,
            10U);
        CHECK_STATUS(status);
    }

#endif

EXIT:
    return status;
}